﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BomberManServer.Utils;

namespace BomberManServer.Gaming.Time
{
    // manage Triggers every cycle
    // manage time between every cycle
    public class Scheduler
    {
        private LinkedList<Trigger> triggers;
        private bool cleared;

        public Scheduler()
        {
            this.triggers = new LinkedList<Trigger>();
            cleared = false;
        }

        // compute all triggers
        public void compute()
        {
            if (triggers.Count == 0)
                return;
            LinkedListNode<Trigger> next;
            LinkedListNode<Trigger> last = triggers.Last;
            
            for(LinkedListNode<Trigger> trigger = triggers.First; trigger != last.Next; trigger = next )
            {
                if (cleared)
                {
                    cleared = false;
                    break;
                }
                if (trigger == null)
                    break;
                next = trigger.Next;
                trigger.Value.compute();
            }
            
        }
        
        // adds a trigger in the scheduler
        public Trigger schedule(int countdown, Trigger.actionHandler action)
        {
            Trigger trigger = new Trigger(countdown, action);
            add(trigger);
            return trigger;
        }
        public void schedule(Trigger trigger)
        {
            trigger.reset();
            add(trigger);
        }
        
        private void add(Trigger trigger) {
            if(trigger.bound) return;
            triggers.AddLast(trigger);
            trigger.bound = true;
            
        }

        private void start()
        {
            cleared = false;
        }

        public void remove(Trigger trigger)
        {
            trigger.bound = false;
            triggers.Remove(trigger);
        }

        public void stop()
        {
            triggers.Clear();
            cleared = true;
        }
    }
}
